c359659fddbe0ef895cfb9cdccebcacec0af094a
[lhc/web/wiklou.git] / includes / mail / EmailNotification.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 * @author Luke Welling lwelling@wikimedia.org
25 */
26
27 /**
28 * This module processes the email notifications when the current page is
29 * changed. It looks up the table watchlist to find out which users are watching
30 * that page.
31 *
32 * The current implementation sends independent emails to each watching user for
33 * the following reason:
34 *
35 * - Each watching user will be notified about the page edit time expressed in
36 * his/her local time (UTC is shown additionally). To achieve this, we need to
37 * find the individual timeoffset of each watching user from the preferences..
38 *
39 * Suggested improvement to slack down the number of sent emails: We could think
40 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
41 * same timeoffset in their preferences.
42 *
43 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
44 */
45 class EmailNotification {
46 protected $subject, $body, $replyto, $from;
47 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
48 protected $mailTargets = array();
49
50 /**
51 * @var Title
52 */
53 protected $title;
54
55 /**
56 * @var User
57 */
58 protected $editor;
59
60 /**
61 * @param User $editor The editor that triggered the update. Their notification
62 * timestamp will not be updated(they have already seen it)
63 * @param Title $title The title to update timestamps for
64 * @param string $timestamp Set the update timestamp to this value
65 * @return int[]
66 */
67 public static function updateWatchlistTimestamp( User $editor, Title $title, $timestamp ) {
68 global $wgEnotifWatchlist, $wgShowUpdatedMarker;
69
70 if ( !$wgEnotifWatchlist && !$wgShowUpdatedMarker ) {
71 return array();
72 }
73
74 $dbw = wfGetDB( DB_MASTER );
75 $res = $dbw->select( array( 'watchlist' ),
76 array( 'wl_user' ),
77 array(
78 'wl_user != ' . intval( $editor->getID() ),
79 'wl_namespace' => $title->getNamespace(),
80 'wl_title' => $title->getDBkey(),
81 'wl_notificationtimestamp IS NULL',
82 ), __METHOD__
83 );
84
85 $watchers = array();
86 foreach ( $res as $row ) {
87 $watchers[] = intval( $row->wl_user );
88 }
89
90 if ( $watchers ) {
91 // Update wl_notificationtimestamp for all watching users except the editor
92 $fname = __METHOD__;
93 $dbw->onTransactionIdle(
94 function () use ( $dbw, $timestamp, $watchers, $title, $fname ) {
95 $dbw->update( 'watchlist',
96 array( /* SET */
97 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
98 ), array( /* WHERE */
99 'wl_user' => $watchers,
100 'wl_namespace' => $title->getNamespace(),
101 'wl_title' => $title->getDBkey(),
102 ), $fname
103 );
104 }
105 );
106 }
107
108 return $watchers;
109 }
110
111 /**
112 * Send emails corresponding to the user $editor editing the page $title.
113 *
114 * May be deferred via the job queue.
115 *
116 * @param User $editor
117 * @param Title $title
118 * @param string $timestamp
119 * @param string $summary
120 * @param bool $minorEdit
121 * @param bool $oldid (default: false)
122 * @param string $pageStatus (default: 'changed')
123 */
124 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
125 $minorEdit, $oldid = false, $pageStatus = 'changed'
126 ) {
127 global $wgEnotifUseJobQ, $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
128
129 if ( $title->getNamespace() < 0 ) {
130 return;
131 }
132
133 // update wl_notificationtimestamp for watchers
134 $watchers = self::updateWatchlistTimestamp( $editor, $title, $timestamp );
135
136 $sendEmail = true;
137 // If nobody is watching the page, and there are no users notified on all changes
138 // don't bother creating a job/trying to send emails
139 // $watchers deals with $wgEnotifWatchlist
140 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
141 $sendEmail = false;
142 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
143 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
144 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
145 if ( $wgEnotifUserTalk
146 && $isUserTalkPage
147 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
148 ) {
149 $sendEmail = true;
150 }
151 }
152 }
153
154 if ( !$sendEmail ) {
155 return;
156 }
157
158 if ( $wgEnotifUseJobQ ) {
159 $params = array(
160 'editor' => $editor->getName(),
161 'editorID' => $editor->getID(),
162 'timestamp' => $timestamp,
163 'summary' => $summary,
164 'minorEdit' => $minorEdit,
165 'oldid' => $oldid,
166 'watchers' => $watchers,
167 'pageStatus' => $pageStatus
168 );
169 $job = new EnotifNotifyJob( $title, $params );
170 JobQueueGroup::singleton()->lazyPush( $job );
171 } else {
172 $this->actuallyNotifyOnPageChange(
173 $editor,
174 $title,
175 $timestamp,
176 $summary,
177 $minorEdit,
178 $oldid,
179 $watchers,
180 $pageStatus
181 );
182 }
183 }
184
185 /**
186 * Immediate version of notifyOnPageChange().
187 *
188 * Send emails corresponding to the user $editor editing the page $title.
189 *
190 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
191 * @param User $editor
192 * @param Title $title
193 * @param string $timestamp Edit timestamp
194 * @param string $summary Edit summary
195 * @param bool $minorEdit
196 * @param int $oldid Revision ID
197 * @param array $watchers Array of user IDs
198 * @param string $pageStatus
199 * @throws MWException
200 */
201 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
202 $oldid, $watchers, $pageStatus = 'changed' ) {
203 # we use $wgPasswordSender as sender's address
204 global $wgEnotifWatchlist;
205 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
206
207 # The following code is only run, if several conditions are met:
208 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
209 # 2. minor edits (changes) are only regarded if the global flag indicates so
210
211 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
212
213 $this->title = $title;
214 $this->timestamp = $timestamp;
215 $this->summary = $summary;
216 $this->minorEdit = $minorEdit;
217 $this->oldid = $oldid;
218 $this->editor = $editor;
219 $this->composed_common = false;
220 $this->pageStatus = $pageStatus;
221
222 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
223
224 Hooks::run( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
225 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
226 throw new MWException( 'Not a valid page status!' );
227 }
228
229 $userTalkId = false;
230
231 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
232 if ( $wgEnotifUserTalk
233 && $isUserTalkPage
234 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
235 ) {
236 $targetUser = User::newFromName( $title->getText() );
237 $this->compose( $targetUser );
238 $userTalkId = $targetUser->getId();
239 }
240
241 if ( $wgEnotifWatchlist ) {
242 // Send updates to watchers other than the current editor
243 $userArray = UserArray::newFromIDs( $watchers );
244 foreach ( $userArray as $watchingUser ) {
245 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
246 && ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) )
247 && $watchingUser->isEmailConfirmed()
248 && $watchingUser->getID() != $userTalkId
249 ) {
250 if ( Hooks::run( 'SendWatchlistEmailNotification', array( $watchingUser, $title, $this ) ) ) {
251 $this->compose( $watchingUser );
252 }
253 }
254 }
255 }
256 }
257
258 global $wgUsersNotifiedOnAllChanges;
259 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
260 if ( $editor->getName() == $name ) {
261 // No point notifying the user that actually made the change!
262 continue;
263 }
264 $user = User::newFromName( $name );
265 $this->compose( $user );
266 }
267
268 $this->sendMails();
269 }
270
271 /**
272 * @param User $editor
273 * @param Title $title
274 * @param bool $minorEdit
275 * @return bool
276 */
277 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
278 global $wgEnotifUserTalk;
279 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
280
281 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
282 $targetUser = User::newFromName( $title->getText() );
283
284 if ( !$targetUser || $targetUser->isAnon() ) {
285 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
286 } elseif ( $targetUser->getId() == $editor->getId() ) {
287 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
288 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
289 && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
290 ) {
291 if ( !$targetUser->isEmailConfirmed() ) {
292 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
293 } elseif ( !Hooks::run( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
294 wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
295 } else {
296 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
297 return true;
298 }
299 } else {
300 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
301 }
302 }
303 return false;
304 }
305
306 /**
307 * Generate the generic "this page has been changed" e-mail text.
308 */
309 private function composeCommonMailtext() {
310 global $wgPasswordSender, $wgNoReplyAddress;
311 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
312 global $wgEnotifImpersonal, $wgEnotifUseRealName;
313
314 $this->composed_common = true;
315
316 # You as the WikiAdmin and Sysops can make use of plenty of
317 # named variables when composing your notification emails while
318 # simply editing the Meta pages
319
320 $keys = array();
321 $postTransformKeys = array();
322 $pageTitleUrl = $this->title->getCanonicalURL();
323 $pageTitle = $this->title->getPrefixedText();
324
325 if ( $this->oldid ) {
326 // Always show a link to the diff which triggered the mail. See bug 32210.
327 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
328 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
329 ->inContentLanguage()->text();
330
331 if ( !$wgEnotifImpersonal ) {
332 // For personal mail, also show a link to the diff of all changes
333 // since last visited.
334 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
335 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
336 ->inContentLanguage()->text();
337 }
338 $keys['$OLDID'] = $this->oldid;
339 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
340 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
341 } else {
342 # clear $OLDID placeholder in the message template
343 $keys['$OLDID'] = '';
344 $keys['$NEWPAGE'] = '';
345 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
346 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
347 }
348
349 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
350 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
351 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
352 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
353 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
354
355 if ( $this->editor->isAnon() ) {
356 # real anon (user:xxx.xxx.xxx.xxx)
357 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
358 ->inContentLanguage()->text();
359 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
360
361 } else {
362 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
363 ? $this->editor->getRealName() : $this->editor->getName();
364 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
365 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
366 }
367
368 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
369 $keys['$HELPPAGE'] = wfExpandUrl(
370 Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
371 );
372
373 # Replace this after transforming the message, bug 35019
374 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
375
376 // Now build message's subject and body
377
378 // Messages:
379 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
380 // enotif_subject_restored, enotif_subject_changed
381 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
382 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
383
384 // Messages:
385 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
386 // enotif_body_intro_restored, enotif_body_intro_changed
387 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
388 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
389 ->text();
390
391 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
392 $body = strtr( $body, $keys );
393 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
394 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
395
396 # Reveal the page editor's address as REPLY-TO address only if
397 # the user has not opted-out and the option is enabled at the
398 # global configuration level.
399 $adminAddress = new MailAddress( $wgPasswordSender,
400 wfMessage( 'emailsender' )->inContentLanguage()->text() );
401 if ( $wgEnotifRevealEditorAddress
402 && ( $this->editor->getEmail() != '' )
403 && $this->editor->getOption( 'enotifrevealaddr' )
404 ) {
405 $editorAddress = MailAddress::newFromUser( $this->editor );
406 if ( $wgEnotifFromEditor ) {
407 $this->from = $editorAddress;
408 } else {
409 $this->from = $adminAddress;
410 $this->replyto = $editorAddress;
411 }
412 } else {
413 $this->from = $adminAddress;
414 $this->replyto = new MailAddress( $wgNoReplyAddress );
415 }
416 }
417
418 /**
419 * Compose a mail to a given user and either queue it for sending, or send it now,
420 * depending on settings.
421 *
422 * Call sendMails() to send any mails that were queued.
423 * @param User $user
424 */
425 function compose( $user ) {
426 global $wgEnotifImpersonal;
427
428 if ( !$this->composed_common ) {
429 $this->composeCommonMailtext();
430 }
431
432 if ( $wgEnotifImpersonal ) {
433 $this->mailTargets[] = MailAddress::newFromUser( $user );
434 } else {
435 $this->sendPersonalised( $user );
436 }
437 }
438
439 /**
440 * Send any queued mails
441 */
442 function sendMails() {
443 global $wgEnotifImpersonal;
444 if ( $wgEnotifImpersonal ) {
445 $this->sendImpersonal( $this->mailTargets );
446 }
447 }
448
449 /**
450 * Does the per-user customizations to a notification e-mail (name,
451 * timestamp in proper timezone, etc) and sends it out.
452 * Returns true if the mail was sent successfully.
453 *
454 * @param User $watchingUser
455 * @return bool
456 * @private
457 */
458 function sendPersonalised( $watchingUser ) {
459 global $wgContLang, $wgEnotifUseRealName;
460 // From the PHP manual:
461 // Note: The to parameter cannot be an address in the form of
462 // "Something <someone@example.com>". The mail command will not parse
463 // this properly while talking with the MTA.
464 $to = MailAddress::newFromUser( $watchingUser );
465
466 # $PAGEEDITDATE is the time and date of the page change
467 # expressed in terms of individual local time of the notification
468 # recipient, i.e. watching user
469 $body = str_replace(
470 array( '$WATCHINGUSERNAME',
471 '$PAGEEDITDATE',
472 '$PAGEEDITTIME' ),
473 array( $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
474 ? $watchingUser->getRealName() : $watchingUser->getName(),
475 $wgContLang->userDate( $this->timestamp, $watchingUser ),
476 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
477 $this->body );
478
479 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
480 }
481
482 /**
483 * Same as sendPersonalised but does impersonal mail suitable for bulk
484 * mailing. Takes an array of MailAddress objects.
485 * @param MailAddress[] $addresses
486 * @return Status|null
487 */
488 function sendImpersonal( $addresses ) {
489 global $wgContLang;
490
491 if ( empty( $addresses ) ) {
492 return null;
493 }
494
495 $body = str_replace(
496 array( '$WATCHINGUSERNAME',
497 '$PAGEEDITDATE',
498 '$PAGEEDITTIME' ),
499 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
500 $wgContLang->date( $this->timestamp, false, false ),
501 $wgContLang->time( $this->timestamp, false, false ) ),
502 $this->body );
503
504 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
505 }
506
507 }